<template>
  <div>
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        v-model.trim="keywords"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        class="search-inp"
        @focus="isShowResult = false"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <!-- 搜索历史/记录/结果 -->
    <!--动态组件 component :is="组件名" -->
    <component
      :keywords="keywords"
      :is="componentName"
      @update-keywords="onSearch"
    />
  </div>
</template>

<script>
import searchHistory from "./components/SearchHistory.vue";
import SearchSuggestions from "./components/SearchSuggestions.vue";
import SearchResult from "./components/SearchResult.vue";
import { mapMutations, mapState } from "vuex";
export default {
  name: "search",
  components: {
    searchHistory,
    SearchSuggestions,
    SearchResult
  },
  data() {
    return {
      keywords: "",
      isShowResult: false // 记录是否触发了搜索事件
    };
  },
  computed: {
    ...mapState(["histories"]),
    componentName() {
      // 绑定focus事件,初始化onSearch事件,把this.isShowResult 改为false
      // 如果输入框没有实际的内容,就渲染搜索结果
      if (this.keywords === "") {
        return "searchHistory";
      }
      // keywords一定有值,要么渲染搜索搜索建议,要么渲染搜索结果
      // 搜索结果是触发了onSearch事件
      if (this.isShowResult) {
        return "SearchResult";
      }
      // 如果代码能走到这里,既不渲染搜索历史,也不渲染搜索结果,直接渲染搜索建议,所以直接return
      return "SearchSuggestions";
    }
  },
  methods: {
    ...mapMutations(["SET_HISTORIES"]),
    onSearch(val) {
      // 更新keywords
      this.keywords = val;

      let newHistories = [this.keywords, ...this.histories];
      // 去重
      newHistories = [...new Set(newHistories)];
      // 存到vuex
      this.SET_HISTORIES(newHistories);

      // 触发搜索事件,就把this.isShowResult 改为true;
      this.isShowResult = true;
    },
    onCancel() {
      // 触发取消，先清空keywords，再触发取消事件
      if (this.keywords === "") {
        this.$router.go(-1);
      } else {
        this.keywords = "";
      }
      // this.$toast("取消");
    }
  }
};
</script>

<style scoped lang="less">
.search-inp {
  .van-search__action {
    color: #fff;
  }
}
</style>
